<?php
namespace app\api\service;
use app\api\model\HotOrder;
use app\api\model\Order;
use app\api\model\Project;
use app\api\model\ProjectOrder;
use app\api\model\TopOrder;
use GatewayWorker\Lib\Db;
use think\Exception;
use think\exception\ValidateException;
use think\Log;
use Yansongda\Pay\Pay;

class PayService
{
    protected $config = [
        'app_id' => 'wxb3c0d8cf5fa714a5', // 公众号 APPID
        'miniapp_id' => 'wxb3c0d8cf5fa714a5', // 小程序 APPID
        'mch_id' => '1626301086',
        'key' => '91bb9370f22699f87c618c6acd7658ec',
        'notify_url' => 'https://yuewan.suomaikeji.com/index.php/api/pay/notify',
        'cert_client' => ROOT_PATH.'public/cert/apiclient_cert.pem', // optional，退款等情况时用到
        'cert_key' => ROOT_PATH.'public/cert/apiclient_key.pem',// optional，退款等情况时用到
        'log' => [ // optional
            'file' => './logs/wechat.log',
            'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
            'type' => 'single', // optional, 可选 daily.
            'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
        ],
        'http' => [ // optional
            'timeout' => 5.0,
            'connect_timeout' => 5.0,
            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
        ],
        'mode' => 'normal', // optional, dev/hk;当为 `hk` 时，为香港 gateway。
    ];

    public function index($data)
    {
        $order = [
            'out_trade_no' => $data['order_no'],
            'total_fee' => $data['amount']*100, // **单位：分**
            'body' => $data['title']?:'订单支付',
            'openid' => $data['openid'],
            'attach' => json_encode(['type'=>$data['type']]),
        ];
        Log::info(json_encode($order));
        return Pay::wechat($this->config)->miniapp($order);
    }

    public function notify()
    {
        $pay = Pay::wechat($this->config);
        try{
            $data = $pay->verify(); // 是的，验签就这么简单！
            Log::record('回调'.json_encode($data));

            if($res['error']) throw new Exception($res['msg']);
            Log::record('订单处理错误'.$res['msg']);
        } catch (Exception $e) {
             exit($e->getMessage());
        }
        return $pay->success()->send();
    }
    /**
     * 退款回调
     * */
    public function refund_notify()
    {
        $pay = Pay::wechat($this->config);
        try{
            $data = $pay->verify(null,true); // 是的，验签就这么简单！
            Log::record('回调'.json_encode($data));
            (new ProjectOrder())->refundSuccess($data);
        } catch (Exception $e) {
            exit($e->getMessage());
        }
        return $pay->success()->send();// laravel 框架中请直接 `return $pay->success()`
    }
    /**
     * 申请退款API
     */
    public function refund($order_no,$trade_id, $refund_fee)
    {
        $this->config['notify_url'] = 'https://yuewan.suomaikeji.com/index.php/api/pay/notify_refund';
        $refund_params = [
            'out_refund_no' =>"R".$order_no,
            'refund_fee' =>$refund_fee,
            'total_fee' =>$refund_fee,
            'transaction_id' =>$trade_id,
            'out_trade_no' =>$order_no,
        ];
        $result = Pay::wechat($this->config)->refund($refund_params);
        // 请求失败
        if (empty($result)) {
            throw new ValidateException(['msg' => '微信退款api请求失败']);
        }
        // 请求失败
        if ($result['code'] === '10000') {
            return true;
        }else{
            throw new ValidateException(['msg' => $result['msg']]);
        }
    }
}